(function () {
    'use strict';

    var app = angular.module('AuthService', []);

    app.factory('authService', ['$rootScope', 'commonConfig', 'httpService', 'loginInfo',
        function ($rootScope, commonConfig, httpService, loginInfo) {

            function changeAuth(loggedIn) {
                $rootScope.$broadcast('loginStatusChanged', loggedIn);
            }

            return {
                login: function (account, passWord, returnAuth) {
                    var loggedIn = false;
                    if (commonConfig.useDatabase) {
                        //Todo:数据库操作
                    } else {
                        var httpOptions = {
                            method: "GET",
                            url: "jsonData/user.json",
                            encoding: "UTF-8"
                        };
                        return httpService.createService(httpOptions).success(
                            function (data, status, headers, config, statusText) {
                                var users = data.users;
                                angular.forEach(users, function (user) {
                                    if (angular.equals(user.account, account) && angular.equals(user.passWord, passWord)) {
                                        loggedIn = true;
                                        user.LoginTime = new Date();
                                        loginInfo.setUser(user);
                                        loginInfo.setLoginStatus(loggedIn);
                                    }
                                });
                                changeAuth(loggedIn);
                                returnAuth(loggedIn);
                            }).error(
                            function (data, status, headers, config, statusText) {
                                alert('error');
                                changeAuth(loggedIn);
                                returnAuth(loggedIn);
                            });

                    }
                }
            };

        }]);
})();